/**
 * Project Name:jh
 * File Name:SocketUtils.java
 * Package Name:com.jh.utils
 * Date:下午5:32:58
 * Copyright (c) 2021, LZ All Rights Reserved.
 *
*/

package com.jh.utils;

import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Description: <br/>
 * Date: 下午5:32:58 <br/>
 * 
 * @author lz E-mail:withitren@outlook.com
 * @version
 * @see
 */
public class SocketUtils {
    static final Logger logger = LoggerFactory.getLogger(SocketUtils.class);

    private static Socket socket = null;

    /*    private SocketUtils() {
    
    }*/

    static {
        init();
    }

    public static Socket getSocket() {
        return socket;
    }

    private static void setSocket(String url, int port) {
        // logger.debug("--->" + "url: " + url + " port: " +
        // Integer.toString(port));
        try {
            SocketUtils.socket = new Socket(url, port);
            logger.debug("--->" + "url: " + url + "  port: " + Integer.toString(port));
        } catch (UnknownHostException e) {
            logger.error(e.getMessage(), e);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
    }

    private static void init() {
        Properties prop = new Properties();
        try {
            prop.load(SocketUtils.class.getResourceAsStream("/appConfig.properties"));
            // throw new Exception("OK!");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        String url = prop.getProperty("tcpUrl", "localhost");
        String portStr = prop.getProperty("tcpPort", "8899");
        int port = Integer.parseInt(portStr);
        setSocket(url, port);
        logger.debug("--->" + "url: " + url + "  portStr: " + portStr);
    }

    public static void closeSocket() {
        try {
            socket.close();
            logger.debug("---> closeSocket");
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
    }

    /*test*/
    public static void main(String[] args) {
        init();
    }
}
